package cn.xueden.edu.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
public class CacheConfig {
    public static final int DEFAULT_MAXSIZE = 288000;
    public static final int DEFAULT_TTL = 1000;

    private SimpleCacheManager cacheManager = new SimpleCacheManager();

    // 定义cache名称、超时时长（秒）、最大容量
    public enum CacheEnum {
        homePage(288000, 1000), // 有效期8个小时 , 最大容量1000
        ;
        CacheEnum(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        private int maxSize = DEFAULT_MAXSIZE; // 最大數量
        private int ttl = DEFAULT_TTL; // 过期时间（秒）

        public int getMaxSize() {
            return maxSize;
        }

        public int getTtl() {
            return ttl;
        }
    }

    // 创建基于Caffeine的Cache Manager
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {
        ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>();
        // 最后一次写入或访问后经过8H过期
        for (CacheEnum c : CacheEnum.values()) {
            caches.add(new CaffeineCache(c.name(), Caffeine.newBuilder().recordStats()
                .expireAfterAccess(c.getTtl(), TimeUnit.SECONDS).maximumSize(c.getMaxSize()).build()));
        }
        cacheManager.setCaches(caches);
        return cacheManager;
    }

}
